/* eslint-disable @typescript-eslint/no-explicit-any */
import axios, { Method } from 'axios'
import i18n, { DEFAULT_LNG, LNG_MAP } from '../../react-i18next-config';
import { fetchToken, logout, unsupport } from '../../utils/user';
import { isDev, platform } from '../../utils/check';
import Recaptcha from '../../google/recaptcha';
import { URL_RECAPTCHA } from './url';

const BASE_URL = process.env.REACT_APP_REQUEST_BASE_URL

let currentLng = 0;

const checkLanguage = () => {
    const defaultLanguage = LNG_MAP[DEFAULT_LNG];
    const language = window.localStorage.getItem('i18nextLng')
    if (!language) {
        return defaultLanguage
    }

    if (i18n.store.data[language]) {
        currentLng = LNG_MAP[language] || defaultLanguage
        return currentLng
    }

    currentLng = defaultLanguage
    return currentLng
}

const fetchLanguage = () => {
    if (!currentLng) {
        return checkLanguage()
    }
    return currentLng
}

const instance = axios.create({
    baseURL: BASE_URL,
    timeout: 8000,
});

const header = () => {
    const lng = fetchLanguage();
    const data: { [key: string]: any } = {
        language: String(lng),
        platform: isDev() ? 'ios' : platform(),
    }

    const token = fetchToken();
    if (token) {
        data['init-data'] = token;
    }

    return data
}

instance.interceptors.request.use((config) => {
    config.headers = config.headers.concat(header());
    return config;
}, error => {
    return error;
})

instance.interceptors.response.use(res => {
    const code: number = res.data.code;
    if (code !== 200 && code !== 0) {
        if (code === 401 || code === 500) {
            logout();
            res.data.msg = ''
        }

        // unsupport os
        if (code === 90101) {
            unsupport();
            res.data.msg = ''
            return
        }

        if (code === 640) {
            res.data.msg = 'sorry, unsupport country'
        }

        // check robot
        if (code === 90200) {
            if (res.config.url !== URL_RECAPTCHA) {
                new Recaptcha().init(true).then(obj => {
                    obj?.render((success, reset) => {
                        if (!success) {
                            reset();
                            return
                        }
                        window.location.reload();
                    })
                });
            }
            res.data.msg = ''
        }

        throw res.data;
    }
    return res.data;
}, error => {
    return error;
})


const request = (method: Method | string, url: string | undefined, params: any, headers?: { [key: string]: string }) => {
    return instance.request({
        method: method,
        url: url,
        params: params,
        headers
    });
}

export const postRequest = (url: string, params?: any, headers?: { [key: string]: string }) => {
    return instance.post(url, params, { headers })
}

export const getRequest = (url: string, params?: object, headers?: { [key: string]: string }) => {
    return request('GET', url, params, headers)
}

export const buildResult = <T>(data: T, code?: number, message?: string) => {
    const success = code === 0 || code === 200
    return {
        data,
        code: success ? 200 : code,
        success,
        message
    }
}

export const customError = (error: { message?: string, msg?: string, code?: string | number }) => {
    return buildResult(undefined, Number(error.code || -1), error.message || error.msg)
}

